<template>
  <view class="page-container">
    <view class="basic-info">
      <!-- 基础信息 -->
      <ve-card>
        <ve-cell label="自有订单号">{{ depositDetail.orderCode }}</ve-cell>
        <ve-cell label="承租人">{{ depositDetail.memberNamePhone }}</ve-cell>
        <ve-cell-price label="剩余可操作金额" :value="depositDetail.availableDepositAmount" />
        <ve-cell label="已扣款次数" style="margin-bottom: 0">
          <view class="">
            <view class="">
              {{ `${depositDetail.cutPaymentNum || 0} 次` }}
            </view>
            <!-- 剩余可扣款次数 x 次 -->
            <view class="surplus-num"> 剩余可扣款次数 {{ depositDetail.surplusNum }} 次</view>
          </view>
        </ve-cell>
      </ve-card>
      <!-- 基础表单 -->
      <ve-card style="margin-bottom: 0">
        <ve-form ref="veFormRef" :model="form" :rules="rules">
          <ve-form-item label="选择押金抵扣类型" prop="deductionType" required>
            <remote-select
              type="dict"
              :outData="deductionTypeEnums"
              :label="form.deductionTypeName"
              v-model="form.deductionType"
              multiple
              title="选择押金抵扣类型"
              @change="onDeductionTypeChange"
            />
          </ve-form-item>
          <ve-form-item label="结算时间" prop="paymentTime" required>
            <ve-date-picker v-model="form.paymentTime" />
          </ve-form-item>
          <ve-form-item label="客户名称" prop="customerName" required>
            <ve-input v-model="form.customerName" placeholder="请输入" :maxlength="20" />
          </ve-form-item>
          <ve-form-item label="结算备注" prop="settlementRemark" labelPosition="top">
            <ve-input type="textarea" v-model="form.settlementRemark" placeholder="请输入" :maxlength="200" />
          </ve-form-item>
          <ve-form-item label="上传凭证" prop="fileIdList" labelPosition="top" :borderBottom="false">
            <ve-upload v-model="form.fileIdList" max-count="10"></ve-upload>
          </ve-form-item>
        </ve-form>
      </ve-card>
    </view>
    <!-- 费用信息 -->
    <fee-info
      ref="feeInfoRef"
      :deductionSum="deductionSum"
      :depositDetail="depositDetail"
      v-model:orderFeeList="form.orderFeeList"
      v-model:violationFeeList="form.violationFeeList"
    />
    <!-- 间距 -->
    <ve-gap size="120" v-if="form.deductionType.length > 0" />
    <!-- 底部容器 -->
    <ve-bottom-box>
      <view class="bottom-wrapper">
        <block v-if="form.deductionType.length > 0">
          <view class="summary">
            {{ summaryLabel }}
            <view class="summary-amount">{{ deductionSum }}</view>
            <view class="summary-amount-unit">元</view>
          </view>
          <view class="line"></view>
        </block>
        <ve-button type="primary" :loading="okLoading" @click="onConfirm" size="long">确认扣款</ve-button>
      </view>
    </ve-bottom-box>
  </view>
</template>
<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { getSOrderDepositDetail, cutPayment } from '@/api/order/sOrder'
  import feeInfo from './components/free-deposit-deduction/fee-info.vue'
  import { decimalAddition } from '@/utils/index'
  import useToast from '@/hooks/useToast'
  import dayjs from 'dayjs'

  const props = defineProps({
    orderId: {
      type: [String, Number],
    },
  })

  const feeInfoRef = ref(null)
  const form = ref({
    deductionType: [],
  })
  const veFormRef = ref(null)
  const rules = ref({
    deductionType: {
      required: true,
      message: '请选择押金抵扣类型',
    },
    paymentTime: {
      required: true,
      message: '请选择结算时间',
    },
    customerName: {
      required: true,
      message: '请输入客户名称',
    },
  })

  const deductionTypeEnums = ref([
    { label: '租车费用', value: 0 },
    { label: '违章费用', value: 1 },
  ])

  // 合计的label
  const summaryLabel = computed(() => {
    let label = '本次押金抵扣合计：'
    // 选中的押金抵扣类型
    const selectDeductionTypes = form.value.deductionType
    if (selectDeductionTypes && selectDeductionTypes.length > 0) {
      const typeNames = selectDeductionTypes.map((type) => {
        return type == 0 ? '租车' : '违章'
      })
      label = `本次押金抵扣合计（${typeNames.join('、')}）：`
    }
    return label
  })

  // 选择押金抵扣类型
  const onDeductionTypeChange = (_, options) => {
    if (options && options.length > 0) {
      const labels = options.map((item) => item.label)
      form.value.deductionTypeName = labels.join(' | ')
    } else {
      form.value.deductionTypeName = ''
    }
    // feeInfoRef
    feeInfoRef.value.handleTypeChange(options)
  }

  // 押金信息
  const depositDetail = ref({})
  const getDepositDetail = () => {
    const id = props.orderId
    getSOrderDepositDetail({ orderId: id, orderType: 1 }).then((res) => {
      const result = res.result
      if (result) {
        // 承租人信息
        const temp = []
        if (result.memberName) temp.push(result.memberName)
        if (result.memberPhone) temp.push(result.memberPhone)
        result.memberNamePhone = temp.join(' | ')
      }
      depositDetail.value = result

      // 默认值
      form.value.paymentTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      form.value.customerName = result.memberName
    })
  }

  // 抵押合计金额
  const deductionSum = computed(() => {
    let sum = 0
    const orderFeeList = form.value.orderFeeList
    const violationFeeList = form.value.violationFeeList
    if (orderFeeList && orderFeeList.length > 0) {
      orderFeeList.forEach((order) => {
        sum = decimalAddition(sum, order.realAmount)
      })
    }
    if (violationFeeList && violationFeeList.length > 0) {
      violationFeeList.forEach((order) => {
        sum = decimalAddition(sum, order.cutPaymentAmount)
      })
    }
    return sum
  })
  /**
   * 确认扣款
   */
  const okLoading = ref(false)
  const onConfirm = () => {
    okLoading.value = true
    veFormRef.value.validate((valid) => {
      if (valid) {
        // 本次押金合计抵扣金额需大于0才是有效操作
        if (deductionSum.value > 0) {
          const param = {
            ...form.value,
            depositId: depositDetail.value.id,
          }
          cutPayment(param)
            .then(() => {
              useToast({
                title: '操作成功等待支付宝返回结果',
                duration: 1500,
                icon: 'none',
              }).then(() => {
                uni.navigateBack()
                // 告知上一页面刷新数据
                uni.$emit('refreshData')
              })
            })
            .catch(() => {
              okLoading.value = false
              // 强制刷新
              setTimeout(() => {
                uni.redirectTo({
                  url: `/pages/order/short-order/free-deposit-deduction?orderId=${props.orderId}`,
                })
              }, 500)
            })
        } else {
          okLoading.value = false
          uni.showToast({
            title: '本次押金合计抵扣金额需大于0',
            icon: 'none',
          })
        }
      } else {
        okLoading.value = false
      }
    })
  }

  onMounted(() => {
    getDepositDetail()
  })
</script>
<style lang="less" scoped>
  page {
    background: #f7f8fa;
  }
  .basic-info {
    padding: 24rpx;
    .surplus-num {
      text-align: center;
      height: 44rpx;
      font-size: 30rpx;
      color: #3072f6;
      line-height: 44rpx;
      margin: 16rpx 0 32rpx;
    }
  }
  .bottom-wrapper {
    width: 100%;
    .summary {
      font-size: 32rpx;
      color: #1e1e1e;
      display: flex;
      align-items: baseline;
      .summary-amount {
        font-weight: 600;
        font-size: 48rpx;
        color: #fe615a;
      }
      .summary-amount-unit {
        font-size: 24rpx;
        color: #fe615a;
        margin-left: 8rpx;
      }
    }
    .line {
      width: 100%;
      height: 2rpx;
      background: rgba(216, 216, 216, 0.3);
      margin: 32rpx 0;
    }
  }
</style>
